/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package simple;

import algorithm.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author Pierre
 */
public class ListPopulation implements Population {

    private boolean isSorted = false;
    private List<Individual> individuals;

    public ListPopulation() {
        this.individuals = new ArrayList<Individual>();
    }

    public int getSize() {
        return individuals.size();
    }

    public void add(Individual individual) {
        individuals.add(individual);
        isSorted = false;
    }

    public void add(Individual[] individuals) {
        for (Individual ind : individuals) {
            add(ind);
        }
        isSorted = false;
    }

    public Individual getIndividual(int i) {
        return individuals.get(i);
    }

    public void sort(Environment environment) {
        if (!isSorted) {
            Collections.sort(individuals, new IndividualComparator(environment));
        }
        isSorted = true;
    }

    public void replaceWorst(Individual individual, Environment environment) {
        sort(environment);
        try {
            this.setIndividual(getSize()-1,individual);
        } catch(Exception e) {
            // could not replace, probably i is too large
            throw new RuntimeException("Error replacing worst",e);
        }
    }

    public void setIndividual(int i, Individual individual) throws AlgorithmErrorException {
        individuals.set(i, individual);
    }
}
